import preferences from '@ohos.data.preferences';

class PreferencesUtils {
  prefMap: Map<string, preferences.Preferences> = new Map();

  async loadPreferences(context, name: string) {
    try {
      let pref = await preferences.getPreferences(context, name)
      this.prefMap.set(name, pref);
    } catch (e) {
      console.error("PreferencesUtils: " + e)
    }
  }

  async putPreferences(name: string, key: string, value: preferences.ValueType) {
    if (!this.prefMap.has(name)) {
      console.log("preferences 还未初始化")
      return;
    }
    // 拿到对应的 preferences 去设置值
    let pref = this.prefMap.get(name)
    // 写入数据
    await pref.put(key, value);
    // 刷入 磁盘
    await pref.flush();
  }

  async getPreferences(name: string, key: string, defaultValue: preferences.ValueType) {
    if (!this.prefMap.has(name)) {
      console.log("preferences 还未初始化")
      return;
    }

    let value = await this.prefMap.get(name).get(key, defaultValue);

    return value;
  }

  async deletePreferences(name: string, key: string) {
    if (!this.prefMap.has(name)) {
      console.log("preferences 还未初始化")
      return;
    }
    let pref = this.prefMap.get(name)
    // 删除
    await pref.delete(key);
    // 刷入 磁盘
    await pref.flush();
  }
}

const preferencesUtils = new PreferencesUtils()

export default preferencesUtils as PreferencesUtils
